package com.xaicode.learn.nio;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 19:01
 */
@Slf4j
public class NIOClient {

    public static void main(String[] args) throws IOException {

        // get server socket channel
        SocketChannel socketChannel = SocketChannel.open();
        // to NIO
        socketChannel.configureBlocking(false);
        // connect with server IP and port
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        // connect to server
        // Connects this channel's socket.
        if (!socketChannel.connect(inetSocketAddress)) {
            // Finishes the process of connecting a socket channel.
            while (!socketChannel.finishConnect()) {
                log.info("connect to server make too long, client will not block");
            }
        }

        // connect to server ok
        log.info("connect to server ok");
        // write to socket channel
        String content = RandomUtil.randomString(10);
        ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
        socketChannel.write(buffer);

        // for test
        // Reads the next byte of data from the input stream.
        // This method blocks until input data is available, end of file is detected, or an exception is thrown.
        System.in.read();
    }

}
